const WXBizDataCrypt = require('./WXBizDataCrypt.js')
const requestSync = require('./requestSync.js')
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const SECRET = '3595207be1b3f0840741d51c20b17083';

// 云函数入口函数
exports.main = async(event, context) => {
  const appid = event.appid
  console.log("event: ", event)
  console.log("appid: ", appid)
  const code = event.js_code
  const encryptedData = event.encryptedData
  const iv = event.iv
  const db = cloud.database()
  const openid = event.userInfo.openid
  const oldSessionKey = event.sessionKey;
  var sessionKey;
  if (oldSessionKey === '') {
    console.log('session key should be get again')
    const url = {
      url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid +
        '&secret=' + SECRET +
        '&js_code=' + code +
        '&grant_type=authorization_code'
    }
    const req = await requestSync(url)
    const session = JSON.parse(req);
    console.log('session:', session);
    sessionKey = session.session_key
  } else {
    sessionKey = oldSessionKey
  }
  
  if (sessionKey) {
    const pc = new WXBizDataCrypt(appid, sessionKey);
    const data = pc.decryptData(encryptedData, iv);
    const result = []
    result.push(data);
    result.push({'sessionKey': sessionKey})
    return result;
  }
  return {}
  
}